#include "jobdialog.h"
#include "ui_jobdialog.h"
#include "job.h"
#include "translationrules.h"
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
JobDialog::JobDialog(TranslationRules* rules, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::JobDialog)
{
    ui->setupUi(this);
    m_job = new Job(this);
    m_job->setRules(rules);
    connect(ui->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(showPreview(const QListWidgetItem*)));
    connect(ui->addFilesButton,SIGNAL(clicked()),this,SLOT(onAddFilesClicked()));
    connect(ui->addDirectoryButton,SIGNAL(clicked()),this,SLOT(onAddDirectoryClicked()));
    connect(ui->removeButton,SIGNAL(clicked()),this,SLOT(onRemoveSelectedClicked()));
    connect(ui->buttonBox,SIGNAL(accepted()),this,SLOT(runJob()));
}

JobDialog::~JobDialog()
{
    delete ui;
}

void JobDialog::onAddFilesClicked(){
    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::AnyFile);
    QStringList filePaths;
    if(dialog.exec()){
        filePaths = dialog.selectedFiles();
        if(!filePaths.empty())
            ui->listWidget->addItems(filePaths);
    }
}

void JobDialog::onAddDirectoryClicked(){
    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::AnyFile);
    QDir dir;
    if(dialog.exec()){
        dir = dialog.directory();
        QStringList filePaths;
        filePaths = dir.entryList(QDir::Files|QDir::Readable);
        if(!filePaths.empty())
            ui->listWidget->addItems(filePaths);
    }

}

void JobDialog::onRemoveSelectedClicked(){
    QList<QListWidgetItem*> list = ui->listWidget->selectedItems();
    foreach(QListWidgetItem* l,list)
        ui->listWidget->removeItemWidget(l);
}

void JobDialog::showPreview(const QListWidgetItem* item){
    QString filePath = item->text();
    QFile file(filePath);
    ui->originalTextEdit->clear();
    ui->transformedTextEdit->clear();
    if(file.open(QFile::ReadOnly)){
        QTextStream str(&file);
        QString line = str.readLine();
        while(!line.isNull()){
            ui->originalTextEdit->appendPlainText(line);
            line = str.readLine();
        }
        file.close();

        QString transformed = m_job->m_rules->process(filePath);
        ui->transformedTextEdit->appendPlainText(transformed);
    }
}

void JobDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
void JobDialog::runJob(){

}
